//
//  UserInfoDBManager.swift
//  swiftim
//
//  Created by yangjian on 2023/7/20.
//

import Foundation


let userInfoTableName = "userinfo"


class UserInfoDBManager {
    
    let usernameKey = "id"
    let userInfoKeys = ["nickname","avartarurl","phone","mail","gender","sign","birth","ext"]
    let timestampKey = "t_s"

//    let databaseQueue : FMDatabaseQueue = {
//        guard let appkey = EMClient.shared().options.appkey else {
//            print("没有appkey,无法初始化userinfo的数据库")
//            return FMDatabaseQueue(path:"\(NSHomeDirectory())/Library/Caches/em/temp") ?? FMDatabaseQueue()
//        }
//        if appkey.count < 1 {
//            print("没有appkey,无法初始化userinfo的数据库")
//            return FMDatabaseQueue(path:"\(NSHomeDirectory())/Library/Caches/em/temp") ?? FMDatabaseQueue()
//        }
//        let directoryPath = "\(NSHomeDirectory())/Library/Caches/em/\(appkey)"
//        var isDirectory : ObjCBool = false
//        let isExit = FileManager.default.fileExists(atPath: directoryPath, isDirectory: &isDirectory)
//        if !(isExit && isDirectory.boolValue) {
//            try? FileManager.default.createDirectory(atPath: directoryPath, withIntermediateDirectories: true)
//        }
//        let dbPath = "\(directoryPath)/userinfo.db"
//        return FMDatabaseQueue(path: dbPath) ?? FMDatabaseQueue()
//    }()
//    var userInfos = [EMUserInfo]()
    let workQueue = queue_bing(label: "UserInfoDBManager_queue")
    let objLock = NSObject()
    let timeout_interval : Int64 = 7*24*3600
    var database : FMDatabase = {
        let directoryPath = directory_userInfo(appkey: EMClient.shared().options.appkey)
        if directoryPath.count < 1 {
            print("路径有问题,userinfodbmanager")
        }
        let dbPath = "\(directoryPath)/userinfo.db"
        let db = FMDatabase(path: dbPath)
        db.open()
        return db
    }()
    
    static let share = UserInfoDBManager()
    init() {
        self.createTable()
        self.deleteTimeOutUsers()
    }
    deinit {
        self.database.close()
    }
    //创建表
    func createTable(){
        let stmt = "create table if not exists \(userInfoTableName) (\(usernameKey) text PRIMARY KEY NOT NULL,\(userInfoKeys[0]) text,\(userInfoKeys[1]) text, \(userInfoKeys[2]) text,\(userInfoKeys[3]) text,\(userInfoKeys[4]) integer,\(userInfoKeys[5]) text,\(userInfoKeys[6]) text,\(userInfoKeys[7]) text,\(timestampKey) integer)"
        if self.database.executeUpdate(stmt, withArgumentsIn: []) {
            print("创建userinfo表 oc版demo输出:Create table success")
        }else{
            print("创建userinfo表 oc版demo输出:Create table Failed")
        }
//        self.closeDatabase()
    }
    
    func insert(userInfos : [EMUserInfo]){
        print("执行save")
        var stmt = "replace into \(userInfoTableName) (\(usernameKey),\(userInfoKeys.joined(separator: ",")),\(timestampKey)) values "
        var valueTags = [String]()
        var values = [Any]()
        let timestamp = Int64(Date().timeIntervalSince1970)
        objc_sync_enter(self.objLock)
        for userInfo in userInfos {
            valueTags.append("(?,?,?,?,?,?,?,?,?,?)")
            values.append(userInfo.userId ?? "")
            values.append(userInfo.nickname ?? "")
            values.append(userInfo.avatarUrl ?? "")
            values.append(userInfo.phone ?? "")
            values.append(userInfo.mail ?? "")
            values.append(userInfo.gender)
            values.append(userInfo.sign ?? "")
            values.append(userInfo.birth ?? "")
            values.append(userInfo.ext ?? "")
            values.append(timestamp)
        }
        print(values)
        stmt += valueTags.joined(separator: ",")
        if self.database.executeUpdate(stmt, withArgumentsIn: values) {
            print("插入 oc版demo输出:insert success")
        }else{
            print("插入 oc版demo输出:insert fail")
        }
        objc_sync_exit(self.objLock)
    }
    
    //预留方法,没有启用
    func fetchTimeOutUsers(){
        let timestamp = Int64(Date().timeIntervalSince1970)
        let stmt = "select \(usernameKey) from \(userInfoTableName) where \(timestampKey) < \(timestamp - timeout_interval)"
        guard let result = self.database.executeQuery(stmt,withArgumentsIn: []) else {
            print("筛选过期信息:fetchTimeOutUsers fail")
            return
        }
        var usernames = [String]()
        while (result.next()) {
            if let username = result.string(forColumnIndex: 0) {
                usernames.append(username)
            }
        }
        if usernames.count > 0 {
            print("有过期信息-\(usernames)")
        }
    }
    
    //删除过期数据
    func deleteTimeOutUsers(){
        let timestamp = Int64(Date().timeIntervalSince1970)
        let stmt = "delete from \(userInfoTableName) where \(timestampKey) < \(timestamp - timeout_interval)"
        if self.database.executeUpdate(stmt,withArgumentsIn: []) {
            print("删除过期信息:deleteTimeOutUsers success")
        }else{
            print("删除过期信息:deleteTimeOutUsers failure")
        }
    }

    //查询所有
    func selectAll() -> [EMUserInfo] {
        let stmt = "select \(usernameKey),\(userInfoKeys.joined(separator: ",")) from \(userInfoTableName)"
        guard let result = self.database.executeQuery(stmt,withArgumentsIn: []) else {
            print("数据库获取所有:selectAll fail")
            return []
        }
        var userInfos = [EMUserInfo]()
        while (result.next()) {
            let userInfo = EMUserInfo()
            //    let userInfoKeys = ["nickname","avartarurl","phone","mail","gender","sign","birth","ext"]
            userInfo.userId = result.string(forColumnIndex: 0)
            userInfo.nickname = result.string(forColumnIndex: 1)
            userInfo.avatarUrl = result.string(forColumnIndex: 2)
            userInfo.phone = result.string(forColumnIndex: 3)
            userInfo.mail = result.string(forColumnIndex: 4)
            userInfo.gender = Int(result.int(forColumnIndex: 5))
            userInfo.sign = result.string(forColumnIndex: 6)
            userInfo.birth = result.string(forColumnIndex: 7)
            userInfo.ext = result.string(forColumnIndex: 8)
            userInfos.append(userInfo)
        }
        return userInfos
    }
}

////开启与关闭 database不需要调用关闭
//extension UserInfoDBManager {
//    var usedDatabaseCount = 0
//    var databaseStatusLock = NSObject()
//    func openDatabase() -> Bool {
//        objc_sync_enter(databaseStatusLock)
//        usedDatabaseCount += 1
//        //        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(__closeDatabase), object: nil)
//        print("==================打开数据库")
//        let success = self.database.open()
//        if !success {
//            print("打开数据库失败")
//        }
//        objc_sync_exit(databaseStatusLock)
//        return success
//    }
//    func closeDatabase() {
//        objc_sync_enter(databaseStatusLock)
//        print("==================将要关闭数据库:2秒后")
//        usedDatabaseCount -= 1
//        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {[unowned self] in
//            self .__closeDatabase()
//        }
//        objc_sync_exit(databaseStatusLock)
//    }
//    @objc func __closeDatabase(){
//        objc_sync_enter(databaseStatusLock)
//        if usedDatabaseCount < 1 {
//            if self.database.isOpen {
//                print("+++++++++++++++++++++++++++++++++++已经关闭")
//                self.database.close()
//            }else{
//                print("+++++++++++++++++++++++++++++++++++数据库已经处于关闭状态")
//            }
//            return
//        }else{
//            print("++++++++取消关闭或已经关闭,不再需要关闭操作")
//        }
//        objc_sync_exit(databaseStatusLock)
//    }
//}
